// pages/addGoods/addGoods.js
var store = require('./../../utils/store')
var WXAPI = require('./../../wxApi/main')
import WxValidate from './../../utils/wxValidate'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 添加商品信息
    goodsInfo: {
      category: "", // 分类(多个分类以英文逗号隔开)
      describe: "", // 商品描述
      id: "", // spu主键编号,传递作修改操作，不传作新增操作
      img: "", // 商品通用图片
      name: "", // 商品名称
      number: "", // sku描述信息
      price: "", // 商品价格(单位为分)
      specifications: "", // 规格(多个规格以英文逗号隔开)
      shopId: "", // 店铺编号
      aspectRatio: "" // 图片宽高比
    },
    imgList: [],
    uploadImageList: [],
    typeList: [],
    specsList: [],
    typeSelectList: [],
    specsSelectLsit: [],
    shopNameList: [],
    shopList: [],
    modalName: '',
    addTitle: '',
    // 添加类型信息
    addInfo: {
      storeId: '',
      businessId: '',
      categoryName: '',
      specName: ''
    }
  },
  // 数据双向绑定
  inputedit: function (e) {
    // 1. input 和 info 双向数据绑定
    let dataset = e.currentTarget.dataset;
    //data-开头的是自定义属性，可以通过dataset获取到，dataset是一个json对象，有obj和item属性，可以通过这两个实现双向数据绑定，通过更改这两个值，对不同name的变量赋值
    let value = e.detail.value;
    this.data[dataset.obj][dataset.item] = value;
    this.setData({
      obj: this.data[dataset.obj]
    });
    if (value) {
      this.data[dataset.tips] = ''
      let tips = dataset.tips
      this.setData({
        [tips]: this.data[dataset.tips]
      });
    }
  },

  // 表单验证
  initValidate() {
    let rules = {
      name: {
        required: true
      },
      price: {
        required: true
      },
      number: {
        required: true
      },
      img: {
        required: true,
      },
      describe: {
        required: true,
      },
      shop: {
        required: true
      },
      type: {
        required: true,
      },
      specs: {
        required: true,
      }
    }

    let message = {
      name: {
        required: '请输入商品名称'
      },
      price: {
        required: '请输入商品单价'
      },
      number: {
        required: '请输入商品数量'
      },
      img: {
        required: '请上传商品图片'
      },
      describe: {
        required: '请输入商品描述'
      },
      shop: {
        required: '请选择一个店铺'
      },
      type: {
        required: '请选择商品分类'
      },
      specs: {
        required: '请选择商品规格'
      }
    }
    //实例化当前的验证规则和提示消息
    this.WxValidate = new WxValidate(rules, message);
  },

  // 计算图片高宽比
  imgH(e) {
    let goodsInfo = this.data.goodsInfo
    goodsInfo.aspectRatio = e.detail.height / e.detail.width
    this.setData({
      goodsInfo: goodsInfo
    })
  },

  // 上传图片
  ChooseImage() {
    let that = this
    let goodsInfo = this.data.goodsInfo
    wx.showLoading({
      title: '图片上传中...',
      mask: true
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 2000)
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        console.log(res.tempFilePaths)
        // 显示图片
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }
        // 上传图片
        WXAPI.upload({
          file: res.tempFilePaths[0]
        }).then(function (res) {
          wx.hideLoading()
          res = JSON.parse(res)
          // console.log(res.data)
          if (res.code == 200) {
            that.data.uploadImageList.push(res.data)
            goodsInfo.img = that.data.uploadImageList.join(',')
            that.setData({
              goodsInfo: goodsInfo,
              noImg: ''
            })
          } else {
            wx.showToast({
              title: '图片上传失败',
              icon: 'none',
              duration: 3000
            })
          }
        }).catch(function (e) {
          console.log(e)
          wx.showToast({
            title: e.msg,
            icon: 'none',
            duration: 3000
          })
        })
      }
    });
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '删除提示',
      content: '确定要删除这张图片吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
  // 选择商品分类、规格
  ChooseCheckbox(e) {
    let that = this
    var dataset = e.currentTarget.dataset;
    let typeSelectList = this.data.typeSelectList
    let specsSelectLsit = this.data.specsSelectLsit
    let goodsInfo = this.data.goodsInfo
    if (dataset.spacs == '分类') {
      let items = this.data.typeList
      for (let i = 0, lenI = items.length; i < lenI; ++i) {
        if (items[i].id == dataset.id) {
          items[i].checked = !items[i].checked
          if (items[i].checked) {
            typeSelectList.push(items[i].categoryName)
          } else {
            typeSelectList.remove(items[i].categoryName)
          }
        }
        that.setData({
          typeList: items,
          noType: ''
        })
      }
    } else {
      let items = this.data.specsList
      for (let i = 0, lenI = items.length; i < lenI; ++i) {
        if (items[i].id == dataset.id) {
          items[i].checked = !items[i].checked
          if (items[i].checked) {
            specsSelectLsit.push(items[i].specName)
          } else {
            specsSelectLsit.remove(items[i].specName)
          }
        }
      }
      that.setData({
        specsList: items,
        noSpece: ''
      })
    }
    goodsInfo.category = typeSelectList.join(",")
    goodsInfo.specifications = specsSelectLsit.join(",")
    this.setData({
      goodsInfo: goodsInfo
    })
  },
  // 选择店铺
  PickerChange(e) {
    console.log(this.data.shopNameList[e.detail.value]);
    let goodsInfo = this.data.goodsInfo
    let addInfo = this.data.addInfo
    this.data.shopList.map(item => {
      if (item.name == this.data.shopNameList[e.detail.value]) {
        console.log(item.id)
        goodsInfo.shopId = item.id
        addInfo.storeId = item.id
        addInfo.businessId = item.id
        WXAPI.goodsTypeList({
          storeId:item.id
        }).then(res => {
          if (res.code == 200) {
            this.setData({
              index: e.detail.value,
              goodsInfo: goodsInfo,
              addInfo: addInfo,
              noShop: '',
              typeList:res.data
            })
          }
        }).catch(err => {
          console.log(err)
        })
        
        return
      }
    })
  },
  // 模态框控制
  showModal(e) {
    let dataset = e.currentTarget.dataset
    console.log(dataset)
    let that = this
    console.log(that.data.addInfo.storeId)
    if(!that.data.addInfo.storeId){
      wx.showToast({
        title: '请选择店铺',
        icon: 'fail',
        duration: 3000
      })
      return
    }
    that.setData({
      modalName: dataset.target
    })
    if (dataset.specs) {
      that.setData({
        addTitle: "商品规格"
      })
    } else {
      that.setData({
        addTitle: "商品分类"
      })
    }
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  // 添加分类、规格
  add(e) {
    let that = this
    let dataset = e.currentTarget.dataset
    if (this.data.addInfo.storeId) {
      if (dataset.add == "商品分类") {
        WXAPI.addGoodsType(this.data.addInfo).then(res => {
          if (res.code == 200) {
            that.setData({
              modalName: null
            })
            wx.showToast({
              title: '商品分类添加成功',
              icon: 'success',
              duration: 3000
            })
            this.goodsTypeList()
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'fail',
              duration: 3000
            })
          }
        }).catch(err => {
          console.log(err)
        })
      } else {
        WXAPI.addSpecs(this.data.addInfo).then(res => {
          if (res.code == 200) {
            that.setData({
              modalName: null
            })
            wx.showToast({
              title: '商品规格添加成功',
              icon: 'success',
              duration: 3000
            })
            this.getSpecifications()
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'fail',
              duration: 3000
            })
          }
        }).catch(err => {
          console.log(err)
        })
      }
    } else {
      that.setData({
        modalName: null
      })
      wx.showToast({
        title: '请先选择一个店铺',
        icon: 'none',
        duration: 3000
      })
    }
  },
  // 添加商品
  addGoods: function (e) {
    let that = this
    let params = e.detail.value;
    console.log(e)
    //表单元素验证不通过，此处给出相应提示
    if (!this.WxValidate.checkForm(params)) {
      let error = this.WxValidate.errorList;
      console.log(error)
      error.map(item => {
        switch (item.param) {
          case "name":
            //TODO
            that.setData({
              noName: item.msg
            })
            break;
          case "price":
            that.setData({
              noPrice: item.msg
            })
            break;
          case "number":
            that.setData({
              noNum: item.msg
            })
            break;
          case "img":
            that.setData({
              noImg: item.msg
            })
            break;
          case "describe":
            that.setData({
              noDes: item.msg
            })
            break;
          case "shop":
            that.setData({
              noShop: item.msg
            })
            break;
          case "type":
            that.setData({
              noType: item.msg
            })
            break;
          case "specs":
            that.setData({
              noSpece: item.msg
            })
            break;
        }
      })
      return false;
    }

    // 表单验证通过
    wx.showLoading({
      title: '正在添加商品...',
      mask: true
    })
    WXAPI.addGoods(this.data.goodsInfo).then(res => {
      if (res.code == 200) {
        wx.hideLoading()
        wx.showToast({
          title: '商品添加成功',
          icon: 'success',
          duration: 3000
        })
        setTimeout(() => {
          wx.navigateBack({
            success: function (e) {
              var page = getCurrentPages().pop();
              if (page == undefined || page == null) return;
              page.onLoad();
            }
          })
        }, 2000);
      }
    })
  },
  // 获取商品分类
  goodsTypeList() {
    console.log(this.data.addInfo.storeId)
    WXAPI.goodsTypeList({
      storeId:this.data.addInfo.storeId
    }).then(res => {
      // console.log(res)
      if (res.code == 200) {
        this.setData({
          typeList: res.data
        })
      }
    }).catch(err => {
      console.log(err)
    })
  },
  // 获取商品规格
  getSpecifications() {
    WXAPI.getSpecifications().then(res => {
      console.log(res)
      if (res.code == 200) {
        this.setData({
          specsList: res.data
        })
      }
    }).catch(err => {
      console.log(err)
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.goodsTypeList()
    this.getSpecifications()
    this.initValidate()
    // 获取店铺列表
    WXAPI.getShopList({
      checked: 2
    }).then(res => {
      console.log(res)
      if (res.code == 200) {
        let shopNameList = []
        res.data.map(item => {
          shopNameList.push(item.name)
          this.setData({
            shopNameList: shopNameList,
            shopList: res.data
          })
        })
      }
    }).catch(err => {
      console.log(err)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})